package com.ruoyi.user.controller.front;

import com.ruoyi.common.core.constant.TokenConstants;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.user.api.domain.UcenterMember;
import com.ruoyi.user.api.domain.dto.UcenterPwdDto;
import com.ruoyi.user.service.IUcenterMemberService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 前台会员功能模块
 *
 * @author isahino
 * @version 1.0
 * @date 2023/9/22 16:35
 */
@RestController
@RequestMapping("/front_member")
public class FrontUcenterMemberController {
    @Autowired
    private IUcenterMemberService ucenterMemberService;

    /**
     * 会员登录
     */
    @PostMapping("/login")
    public AjaxResult login(@Valid @RequestBody UcenterMember ucenterMember) {
        // 返回token，使用jwt生成
        String token = ucenterMemberService.login(ucenterMember);
        return AjaxResult.success().put(TokenConstants.USER_TOKEN, token);
    }

    /**
     * 会员注册
     */
    @PostMapping("/register")
    public AjaxResult register(@Valid @RequestBody UcenterMember ucenterMember) {
        ucenterMemberService.register(ucenterMember);
        return AjaxResult.success("注册成功");
    }

    /**
     * 会员信息修改
     */
    @PutMapping
    public AjaxResult edit(@RequestBody UcenterMember ucenterMember) {
        if (StringUtils.isEmpty(ucenterMember.getId())) {
            return AjaxResult.error("会员标识为空，请重新登录");
        }
        return ucenterMemberService.updateInfoById(ucenterMember)? AjaxResult.success("信息修改成功"): AjaxResult.error("信息修改失败，请稍后再试");
    }

    /**
     * 会员密码修改
     */
    @PutMapping("/pwd")
    public AjaxResult editPwd(@Valid @RequestBody UcenterPwdDto pwdDto) {
        ucenterMemberService.editPassword(pwdDto);
        return AjaxResult.success("密码修改成功");
    }

    /**
     * 根据token获取用户信息
     */
    @GetMapping("/getMemberInfo")
    public AjaxResult getMemberInfo(HttpServletRequest request) {
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if ("".equals(memberId)) {
            return AjaxResult.error("当前未处于登录状态，请重新登录");
        }
        UcenterMember member = ucenterMemberService.getById(memberId);
        member.setPassword(null);
        return AjaxResult.success(member);
    }
}
